﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using GoToTags.Nfc.Ndef;
using GoToTags.Nfc.Records;

namespace Touch2Like.Tags
{
    public class GitHubRecord : WebsiteRecord
    {
        public string Account { get; set; }

        public override string Url
        {
            get { return string.Format("https://github.com/{0}", Uri.EscapeUriString(this.Account)); }
            set { throw new ArgumentException("The url can not be directly set."); }
        }
        public override string ToString()
        {
            return this.Account;
        }
        public override bool Equals(object obj)
        {
            var gitHubRecord = obj as GitHubRecord;
            return gitHubRecord != null &&
            string.Equals(this.Account, gitHubRecord.Account);
        }
        public override int GetHashCode()
        {
            return (this.Account + "").GetHashCode();
        }
        protected override NdefRecord ToNdefRecord()
        {
            return new NfcUriRecord(this.Url);
        }
        public static GitHubRecord ToGitHubRecord(NdefRecord ndefRecord)
        {
            if (ndefRecord is NfcUriRecord)
            {
                var nfcUriRecord = ndefRecord as NfcUriRecord;
                if (nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.http ||
                nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.https ||
                nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.httpswww ||
                nfcUriRecord.UriPrefix == NfcUriRecord.Prefix.httpwww)
                {
                    return GitHubRecord.FromUrl(nfcUriRecord.ToString());
                }
            }
            return null;
        }
        private static readonly Regex EXPR = new Regex(@"^https?:\/\/github\.com\/(?<account>.+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
        public static GitHubRecord FromUrl(string url)
        {
            if (!string.IsNullOrWhiteSpace(url))
            {
                var matches = EXPR.Matches(url);
                if (matches.Count == 1)
                {
                    var accountGroup = matches[0].Groups["account"];
                    if (accountGroup != null && accountGroup.Success)
                    {
                        var account = accountGroup.Value;
                        if (!string.IsNullOrWhiteSpace(account))
                        {
                            account = Uri.UnescapeDataString(account);
                            var gitHubRecord = new GitHubRecord()
                            {
                                Account = account
                            };
                            return gitHubRecord;
                        }
                    }
                }
            }
            return null;
        }
    }
}
